<template>
  <div>
    <van-pull-refresh
      v-model="refreshLoading"
      @refresh="loadNextPage"
      success-text="刷新成功"
    >
      <van-list
        v-model="loading"
        @load="loadNextPage"
        offset="0"
        :immediate-check="false"
        :finished="finished"
        finished-text="没有更多了"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
      >
        <ArticleItem
          v-for="item in articles"
          :key="item.art_id"
          :articleInfo="item"
        ></ArticleItem>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
// 当组件滚动到底部时，会触发 load 事件自动将 loading 设置成 true
import { getArticleAPI } from '@/api'
import ArticleItem from '@/components/ArticleItem.vue'
export default {
  components: {
    ArticleItem
  },
  props: {
    id: {
      type: [String, Number],
      required: true
    }
  },
  data() {
    return {
      articles: [],
      pre_timestamp: '',
      loading: false,
      finished: false,
      error: false,
      refreshLoading: false
    }
  },
  created() {
    this.getFirstpage()
  },
  methods: {
    // 第一页请求
    async getFirstpage() {
      try {
        const {
          data: { data }
        } = await getArticleAPI(this.id, +new Date())
        // console.log(data)
        this.articles = data.results
        // 更新时间戳
        this.pre_timestamp = data.pre_timestamp
      } catch (error) {
        this.$toast.fail('请刷新')
      }
    },
    // 下拉加载请求
    async loadNextPage() {
      // console.log('加载中')
      try {
        const {
          data: { data }
        } = await getArticleAPI(this.id, this.pre_timestamp)
        // 判断数据的完成的节点 显示finnis字段 停止渲染
        if (!data.pre_timestamp) {
          this.finished = true
        }
        // 保存数据
        // 判断是下滑刷新还是下拉刷新  决定数组添加的位置
        if (this.refreshLoading) {
          this.articles.unshift(...data.results)
        } else {
          this.articles.push(...data.results)
        }

        // 保存新的时间戳
        this.pre_timestamp = data.pre_timestamp
      } catch (error) {
        this.error = true
      } finally {
        // 将load时间激活
        this.loading = false
        this.refreshLoading = false
      }
    }
  }
}
</script>

<style></style>
